package me.zy.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yuzhou on 2017/10/9.
 */
public class Cart implements Serializable {

  private Map<Integer, CartItem> map = new HashMap<>();

  public Cart() {
  }

  /**
   * 购物车商品列表
   * @return
   */
  public List<CartItem> getItems() {
    return new ArrayList<>(map.values());
  }

  /**
   * 添加商品到购物车
   * @param product
   */
  public void addItem(Product product) {
    Integer id = product.getId();
    CartItem item = map.get(id);
    if (item != null) {
      item.increaseQuantity();
    } else {
      map.put(id, new CartItem(product, 1));
    }
  }

  /**
   * 获取购物车商品总价
   * @return
   */
  public Integer getTotalPrice() {
    Integer total = 0;
    for (CartItem item : map.values()) {
      total += item.getTotalPrice();
    }
    return total;
  }
}
